<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI对话功能修复测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }

        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }

        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }

        button:hover {
            background-color: #0056b3;
        }

        .result {
            margin-top: 10px;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 4px;
            white-space: pre-wrap;
            font-family: monospace;
        }

        .success {
            color: green;
        }

        .error {
            color: red;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>AI对话功能修复测试</h1>
        <p>测试服务器是否只返回text字段内容，而不是整个JSON对象</p>

        <div class="test-section">
            <h3>测试1: 流式AI对话</h3>
            <button onclick="testStreamChat()">测试流式对话</button>
            <div id="streamResult" class="result"></div>
        </div>

        <div class="test-section">
            <h3>测试2: 非流式AI对话</h3>
            <button onclick="testSimpleChat()">测试非流式对话</button>
            <div id="simpleResult" class="result"></div>
        </div>

        <div class="test-section">
            <h3>测试3: 直接API调用</h3>
            <button onclick="testDirectAPI()">测试直接API</button>
            <div id="directResult" class="result"></div>
        </div>
    </div>

    <script>
        async function testStreamChat() {
            const resultDiv = document.getElementById('streamResult');
            resultDiv.innerHTML = '测试中...';

            try {
                const response = await fetch('/api/ai/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        prompt: '你好，请简单介绍一下硅材料',
                        temperature: 0.7,
                        max_tokens: 100
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let fullResponse = '';
                let isFinal = false;

                resultDiv.innerHTML = '收到流式响应:<br>';

                while (!isFinal) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');

                    for (const line of lines) {
                        if (line.trim() && line.startsWith('data: ')) {
                            try {
                                const jsonStr = line.substring(6);
                                const data = JSON.parse(jsonStr);

                                // 检查是否只包含content字段
                                const hasOnlyContent = Object.keys(data).length <= 2 &&
                                    data.hasOwnProperty('content') &&
                                    (data.hasOwnProperty('is_final') || Object.keys(data).length === 1);

                                resultDiv.innerHTML += `<div class="${hasOnlyContent ? 'success' : 'error'}">
                                    数据: ${JSON.stringify(data)}
                                    ${hasOnlyContent ? '✅ 只包含text字段内容' : '❌ 包含完整JSON对象'}
                                </div>`;

                                if (data.content) {
                                    fullResponse += data.content;
                                }
                                isFinal = data.is_final || false;
                            } catch (e) {
                                resultDiv.innerHTML += `<div class="error">解析错误: ${e.message}</div>`;
                            }
                        }
                    }
                }

                resultDiv.innerHTML += `<br><strong>完整响应:</strong> ${fullResponse}`;

            } catch (error) {
                resultDiv.innerHTML = `<div class="error">错误: ${error.message}</div>`;
            }
        }

        async function testSimpleChat() {
            const resultDiv = document.getElementById('simpleResult');
            resultDiv.innerHTML = '测试中...';

            try {
                const response = await fetch('/api/ai/chat/simple', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        prompt: '你好，请简单介绍一下碳材料',
                        temperature: 0.7,
                        max_tokens: 100
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();

                // 检查响应结构
                const hasOnlyResponseField = Object.keys(data).length === 1 && data.hasOwnProperty('response');

                resultDiv.innerHTML = `
                    <div class="${hasOnlyResponseField ? 'success' : 'error'}">
                        响应数据: ${JSON.stringify(data, null, 2)}
                        ${hasOnlyResponseField ? '✅ 只包含response字段' : '❌ 包含完整JSON对象'}
                    </div>
                `;

            } catch (error) {
                resultDiv.innerHTML = `<div class="error">错误: ${error.message}</div>`;
            }
        }

        async function testDirectAPI() {
            const resultDiv = document.getElementById('directResult');
            resultDiv.innerHTML = '测试中...';

            try {
                const response = await fetch('http://127.0.0.1:8003/ai/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        prompt: '测试直接连接',
                        temperature: 0.7,
                        max_tokens: 50
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let firstChunk = '';

                const { value } = await reader.read();
                firstChunk = decoder.decode(value);

                // 检查第一个数据块的内容
                const isContentOnly = firstChunk.includes('"content"') &&
                    !firstChunk.includes('"id"') &&
                    !firstChunk.includes('"object"') &&
                    !firstChunk.includes('"created"');

                resultDiv.innerHTML = `
                    <div class="${isContentOnly ? 'success' : 'error'}">
                        第一个数据块: ${firstChunk}
                        ${isContentOnly ? '✅ 只包含content字段' : '❌ 包含完整JSON对象'}
                    </div>
                `;

                reader.releaseLock();

            } catch (error) {
                resultDiv.innerHTML = `<div class="error">错误: ${error.message}</div>`;
            }
        }
    </script>
</body>

</html>